using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ZeroSum.App.Datas;
using ZeroSum.Exceptions;
using ZeroSum.Models;

namespace ZeroSum.App.Filters;

/// <summary>
///     统一返回格式（并将模型验证失败的返回结果转换为业务异常）
/// </summary>
public class ApiResponseFilter : IAsyncResultFilter
{
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        if (context.ModelState.IsValid)
        {
            var data = (context.Result as ObjectResult)?.Value;
            context.Result = new JsonResult(ApiResponse<object?>.Of(ResponseStatus.Success, "请求成功", data));
            await next();
            return;
        }

        // 针对模型验证失败的做处理
        var validateErrors = new List<string>();
        foreach (var stateValue in context.ModelState.Values)
        foreach (var error in stateValue.Errors)
            validateErrors.Add(error.ErrorMessage);
        throw ValidateFailedException.Of(validateErrors);
    }
}